package com.fzy.core.system.action;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.fzy.core.entity.Page;
import com.fzy.core.spring.M;
import com.fzy.core.system.entity.EntityWrapper;
import com.fzy.core.system.entity.PropertyWrapper;
import com.fzy.core.system.service.DbService;
import com.fzy.core.utils.DateUtils;
import com.fzy.core.webwork.BaseAction;
import com.opensymphony.xwork.Preparable;

public class CommonListAction extends BaseAction implements Preparable {
	private static final long serialVersionUID = -8158569399284249116L;
	Page page = new Page();
	EntityWrapper entityWrapper;
	DbService dbService;
	Map q = new HashMap();

	public void prepare() throws Exception {
	}
	
	public String execute() throws Exception {
		entityWrapper = dbService.initEntityWrapper();
		
		dbService.queryPageByMapping(q, entityWrapper, page);
		return "dispatcher:/WEB-INF/jsp/core/system/common-list.jsp";
    }
	
	public String download() throws Exception {
		entityWrapper = dbService.initEntityWrapper();
		
		List list = dbService.queryByMapping(null, entityWrapper);
		//List newList = new ArrayList();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Map m = (Map) iterator.next();
			for (Iterator iterator2 = entityWrapper.getProperties().iterator(); iterator2.hasNext();) {
				PropertyWrapper pw = (PropertyWrapper) iterator2.next();
				String fieldName = pw.getColumnName();
				Object value = m.get(fieldName);
				if(value == null) continue;
				String pattern = pw.getDateFormatShow();
				if(PropertyWrapper.JAVA_DATE.equals(pw.getJavaType())){
					m.put(fieldName, DateUtils.formatSafely((Date)value, pattern));
				}else if(pw.getHasDateFormat() && pw.getHasDateFormatShow()){
					m.put(fieldName, DateUtils.parseDateSafely((String)value, pw.getData().getDateFormat(), pattern));
				}else if(pw.getIsDict()){
					m.put(fieldName, M.getDictNameByTypeAndCode((String)value, pw.getData().getDictType()));
				}
			}
			//newList.add(m);
		}
		
		String entityNameShow = entityWrapper.getData().getNameShow();
		Map m = new HashMap();
		m.put("entityWrapper", entityWrapper);
		m.put("list", list);
		renderTemplate(response, m, "common-list.xml", entityNameShow + ".xml");
		return null;
    }
	
	public void setDbService(DbService dbService) {
		this.dbService = dbService;
	}

	public EntityWrapper getEntityWrapper() {
		return entityWrapper;
	}

	public Page getPage() {
		return page;
	}

	public Map getQ() {
		return q;
	}

}
